<?php
namespace app\common\shopify;

use app\api\model\Product as ProductModel;
use think\facade\Config;
use think\facade\Log;

class ProductService extends BaseClient {
    /**
     * 创建Shopify商品（终极修复版）
     * @param int $productId 本地商品ID
     * @return string Shopify商品ID
     */
    public function createProduct(int $productId) {
        $product = ProductModel::find($productId);
        if (!$product) throw new \Exception('商品不存在');

        // ✅ 构建符合GraphQL Schema的输入结构
        $input = $this->buildProductInput($product);

        // ✅ 通过日志输出完整请求结构（调试关键）
        Log::debug("Shopify请求结构: ".json_encode($input, JSON_PRETTY_PRINT));

        $query = <<<GRAPHQL
mutation productCreate(\$input: ProductInput!) {
  productCreate(input: \$input) {
    product {
      id
      variants(first: 1) {
        edges {
          node {
            id
            inventoryItem { id }
          }
        }
      }
    }
    userErrors { field message }
  }
}
GRAPHQL;

        // ✅ 强制指定API版本头（必须与后台一致）
        $headers = [
            'X-Shopify-Access-Token: ' . Config::get('shopify.access_token'),
            'Content-Type: application/json',
            'X-Shopify-API-Version: 2025-04'
        ];

        $response = $this->graphqlRequest($query, ['input' => $input[0],'media'=>$input[1]], $headers);

        // ✅ 三级错误处理机制
        if ($response === null) {
            throw new \Exception("API请求无响应，请检查网络连接");
        }

        if (!empty($response['errors'])) {
            $errorMsg = json_encode($response['errors']);
            Log::error("GraphQL语法错误: $errorMsg");
            throw new \Exception("API请求格式错误: $errorMsg");
        }

        if (!empty($response['productCreate']['userErrors'])) {
            $errors = json_encode($response['productCreate']['userErrors']);
            Log::error("Shopify业务错误: $errors");
            throw new \Exception("Shopify拒绝请求: $errors");
        }

        return $response['productCreate']['product'];
    }

    /**
     * 构建100%兼容的输入结构
     * @param \app\api\model\Product $product
     * @return array
     */
    private function buildProductInput($product) {
        // ✅ 媒体字段修正（使用images数组）
        $images = [];
        if ($product->photo) {
            foreach (explode(',', $product->photo) as $url) {
                $url = trim($url);
                if (filter_var($url, FILTER_VALIDATE_URL)) {
                    $images[] = ['originalSource' => $url,'mediaContentType'=>'IMAGEIMAGE'];
                }
            }
        }



        return [[
            // ✅ 核心产品字段
            'title' => $product->cname ?: '未命名商品',
            'descriptionHtml' => $product->describe ?: '暂无描述',
            'productType' => $product->category ?: 'Uncategorized',
            'vendor' => $product->brand_name ?: 'Default Vendor',
            'status' => $product->status == 1 ? 'ACTIVE' : 'DRAFT',


            // ✅ Metafields字段
            'metafields' => [
                [
                    'namespace' => 'specs',
                    'key' => 'hashrate',
                    'value' => (string)($product->hashrate ?: '0'),
                    'type' => 'string'
                ],
                [
                    'namespace' => 'specs',
                    'key' => 'power_consumption',
                    'value' => (string)($product->power ?: '0w'),
                    'type' => 'string'
                ]
            ]
        ],$images];
    }
}